﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Concurrent;
namespace HB.Expand
{
    public static class DicExpand
    {
        /// <summary>
        /// 根据条件添加
        /// </summary>
        /// <typeparam name="Tkey"></typeparam>
        /// <typeparam name="Tvalue"></typeparam>
        /// <param name="dic"></param>
        /// <param name="condition"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void AddIf<Tkey, Tvalue>(this Dictionary<Tkey, Tvalue> dic, bool condition, Tkey key, Tvalue value)
        {
            if (condition)
            {
                dic.Add(key, value);
            }
        }
        /// <summary>
        /// 根据条件添加
        /// </summary>
        /// <typeparam name="Tkey"></typeparam>
        /// <typeparam name="Tvalue"></typeparam>
        /// <param name="dic"></param>
        /// <param name="condition"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool AddIf<Tkey, Tvalue>(this ConcurrentDictionary<Tkey, Tvalue> dic, bool condition, Tkey key, Tvalue value)
        {
            if (condition)
            {
                return dic.TryAdd(key, value);
            }
            return false;
        }
        /// <summary>
        /// 根据情况添加
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="hash"></param>
        /// <param name="condition"></param>
        /// <param name="value"></param>
        public static void AddIf<T>(this HashSet<T> hash, bool condition, T value)
        {
            if (condition)
            {
                hash.Add(value);
            }
        }
        /// <summary>
        /// 根据情况添加
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ls"></param>
        /// <param name="condition"></param>
        /// <param name="value"></param>
        public static void AddIf<T>(this List<T> ls, bool condition, T value)
        {
            if (condition)
            {
                ls.Add(value);
            }
        }
        /// <summary>
        /// 尝试获取指定key的值，如果不存在，返回传入的默认值
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <param name="dic"></param>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static T2 TryGetValue<T1, T2>(this Dictionary<T1, T2> dic, T1 key, T2 defaultValue = default)
        {
            if (dic.ContainsKey(key)) { return dic[key]; }
            else
            {
                return defaultValue;
            }
        }
    }
}
